package demo.server.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import demo.BlogContentApi;
import demo.common.constants.Constant;
import demo.common.exception.BlogException;
import demo.common.utils.MailUtil;
import demo.mapper.UserInfoMapper;
import demo.pojo.*;
import demo.common.pojo.UserInfo;
import demo.pojo.response.Result;
import demo.server.UserService;
import demo.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    //todo 这个要通过微服务调用
    @Autowired
    private BlogContentApi blogContentApi;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private MailUtil mailUtil;

    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
        UserInfo userInfo = selectUserInfoByName(user.getUserName());
        if (userInfo == null || userInfo.getId() == null) {
            throw new BlogException("用户不存在");
        }

        if (!SecurityUtil.verify(user.getPassword(), userInfo.getPassword())) {
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //1. 根据博客ID, 获取作者ID
        BlogInfoResponse blogInfo = getBlogInfo(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogInfo == null) {
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogInfo.getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer register(RegisterRequest request) {
        UserInfo userInfo = new UserInfo(null, request.getUserName(), SecurityUtil.encrypt(request.getPassword())
                , request.getGithubUrl(), request.getEmail(), null, null, null);
        userInfoMapper.insert(userInfo);

        redisUtil.set(Constant.REGISTER_PREFIX + String.valueOf(userInfo.getId()), JsonUtil.toJson(userInfo));

        rabbitTemplate.convertAndSend(Constant.EXCHANGE_NAME,"",JsonUtil.toJson(userInfo));

        return userInfo.getId();
    }


    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }

    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }

    private BlogInfoResponse getBlogInfo(Integer blogId) {
        log.info("blogId = {}", blogId);

        Result<BlogInfoResponse> blogInfo = blogContentApi.getBlogDetail(blogId);

        return blogInfo.getData();
    }
}
